<template>
  <n-modal v-model:show="isVisible" title="编辑产品" preset="dialog" @close="onClose" @update:show="onClose" style="height: 650px;width: 700px" @after-leave="clearImages">
    <n-form @submit.prevent="handleSubmit" label-width="120px" class="form-container">
      <!-- 第一行：产品名称 和品牌-->
      <div class="form-row">
        <n-form-item label="产品名称：" path="name">
          <n-input v-model:value="form.name" placeholder="请输入产品名称" />
        </n-form-item>

          <n-form-item label="产品分类：" path="category">
              <n-cascader
                      v-model:value="form.categoryId"
                      style="width:160px"
                      :options="option"
                      filterable
              >
              </n-cascader>
          </n-form-item>
          <n-form-item label="供应商：" path="supplier">
              <n-select v-model:value="form.supplierId" :options="suppliers" placeholder="选择供应商" filterable />
          </n-form-item>
      </div>
      <!-- 第二行：产品分类和产品属性 -->
      <div class="form-row">
        <n-form-item label="产品属性：" path="attributes">
          <n-select v-model:value="form.attributeId" :options="attributes" placeholder="选择产品属性" filterable />
        </n-form-item>
          <n-form-item style="margin-left: 10px" label="产品品牌">
              <n-select v-model:value="form.brandId"
                        :options="brands"
                        placeholder="请选择品牌"
                        style="width: 150px"></n-select>
          </n-form-item>
          <n-form-item label="产品状态：" path="type">
              <n-select v-model:value="form.status"
                        :options="statusOptions"
                        placeholder="请选择产品状态"
                        style="width: 150px"></n-select>
          </n-form-item>
      </div>
        <n-form-item label="成本：" path="cost">
            <n-input-number v-model:value="form.cost" placeholder="请输入成本" />
        </n-form-item>
        <span style="font-size: 15px; font-weight: 400; margin-bottom: 10px;">产品展示图(默认第一张图作为产品首图)：</span>
        <div class="form-row">
            <n-flex v-for="(picture, index) in pictures" class="image-container">
                    <n-image
                            :key="index"
                            height="90px;"
                            :src="picture"
                    />
                <div class="delete-icon" @click="handleDelete(index)">
                    <icon-material-symbols:delete-outline style="font-size: 14px;"/> <!-- 使用 Font Awesome 图标库作为示例 -->
                </div>
            </n-flex>
            <n-upload
                    action="#"
                    list-type="image-card"
                    :max="5-pictures.length"
                    multiple
                    @before-upload="beforeUpload"
                    accept="image"
                    @remove="handleRemove"
                    :default-upload="false"/>
        </div>
      <!-- 第四行：成本 -->
        <div class="submit-row">
            <n-form-item label="产品文案：" path="type">
            <n-input
                    v-model:value="form.type"
                    type="textarea"
                    placeholder=""
                    maxlength="200"
                    style="width: 660px;"
                    :autosize="{
                                minRows: 5,
                                maxRows: 8
                              }"
                    show-count
            />
            </n-form-item>
        </div>
      <!-- 提交按钮 -->
      <div class="submit-row">
          <n-button type="primary" native-type="submit" @click="handleSubmit">提交</n-button>
      </div>
    </n-form>
  </n-modal>
</template>

<script setup>
import {h, onMounted, ref, watch} from 'vue';
import {NImage, useMessage} from 'naive-ui';
  import api from "@/api/admin.js";
  import {useRouter} from 'vue-router';
  import {useUserStore} from "@/store/index.js";
  const emit = defineEmits(["updatePage"])
  const brands=ref([])
  const attributes=ref([])
  const range = ref(null)
  const userStore = useUserStore()
  const loading = ref(false)
  const id = userStore.getId();
  const router = useRouter()
  const props = defineProps({
    show1: {
      type: Boolean,
      required: true,
    },
    onClose: {
      type: Function,
      required: true,
    },
    product:{
      type:Object,
      required:true,
    }
  });
  const option = ref([ ])
  const form = ref({
    id:'',
    name: '',
    categoryId: null,
    attributeId: null,
    type: '',
    supplierId: null,
    status: null,
    cost: null,
    brandId:'',
    picture:''
  });
	const pictures = ref([])
  let pictureList = []
  const isVisible = ref(props.show1);
  watch(() => props.show1, (newVal) => {
    isVisible.value = newVal;
  if (newVal) {
    form.value = { ...props.product };
	  if (form.value.picture === null || form.value.picture === "" || !form.value.picture.trim()) {
		  return ""
	  }
	  pictureList = form.value.picture.split(',');
	  pictureList.map((picture) => {
    pictures.value.push(`/api/common/download?name=${picture}`)
    })
    }
  });
let files = []
const beforeUpload = ({file}) => {
	const fileType = ["image/png", "image/jpeg", "image/jpg"]; // 通常包括image/jpeg
	if (!fileType.includes(file.file?.type)) {
		// 如果文件类型不在允许的列表中，显示错误消息并返回false
		$message.error("只能上传png或jpg格式的图片文件，请重新上传");
		return false;
	}
	files.push(file)
	return true;
}
let	imageList = []
const statusOptions = [
	{ label: '开发中', value: '开发中' },
	{ label: '在售', value: '在售' },
	{ label: '下架', value: '下架' },
];
const handleRemove = ({index}) => {
	files = files.filter((_, i) => i !== index);
}
const handleDelete = (index) => {
	pictures.value = pictures.value.filter((_, i) => i !== index);
	pictureList = pictureList.filter((_, i) => i !== index);
}
const uploadImage = async () => {
	try {
		pictureList.map((item) => {
			imageList.push(item)
    })
		// 使用 Promise.all 等待所有 customRequest 调用完成
		await Promise.all(files.map((file) => customRequest(file)));
		// 现在所有的文件都已经上传完成，可以安全地打印 imageList 的长度
		form.value.picture = imageList.join(",")
	} catch (err) {
		$message.error("添加产品失败！");
	}
}
const customRequest = async (file) => {
	try{
		const formData = new FormData();
		formData.append("file", file.file)
		const res = await api.uploadFile(formData)
		if(res.code === 200) {
			imageList.push(res.data)
		}
		else {
			$message.error(res.message)
		}
	}catch (e) {
		$message.error("图片上传失败！")
	}
}
  const handleSubmit = async () => {
    try {
			await uploadImage()
      const res = await api.updateProduct(
        {
          ...form.value,
        }
      );  // 调用更新接口
      if (res.code === 200) {
        emit("updatePage");
      } else {
        $message.error(res.message);
      }
    } catch (err) {
      $message.error("更新失败！");
    } finally {
      clear();
			clearImages()
      props.onClose();
    }
  };
  const clear = () => {
    form.value = {
      id:'',
      name: '',
      categoryId: null,
      attributesId: null,
      type: '',
      supplierId: null,
      status: null,
      cost: null,
      brandId:'',
      picture:[]
    }};
	const clearImages = () => {
		pictureList = []
		files = []
		pictures.value = []
		imageList = []
  }
  const queryAllProductCategory = async  () => {
    try {
      const res = await api.findAllProductCategory()
      if(res.code === 200) {
        // 调用函数生成n-cascader的options
        convertToCascaderOptions(res.data);
      }
      else {
        $message.error(res.message)
      }
    } catch (err) {
      $message.error("获取产品失败！")
    }finally{
      loading.value = false
    }
  }
  const convertToCascaderOptions = (flatData) => {
    const idNodeMap = {}; // 用于映射id到对应的节点对象
    const opt = []; // 最终生成的级联选择器数据
    // 首先，将所有的数据节点放到一个映射表中，方便后续通过ID快速查找
    flatData.forEach(node => {
      idNodeMap[node.id] = { ...node, children: [] };
    });
    // 构建树形结构
    Object.values(idNodeMap).forEach(node => {
      if (node.parentCategoryId === null) {
        // 如果parentId为null，则该节点是根节点
        opt.push(node);
      } else {
        // 否则，将该节点添加到其父节点的children数组中
        const parentNode = idNodeMap[node.parentCategoryId];
        if (parentNode) {
          parentNode.children.push(node);
        }
      }
    });
    console.log(opt)
    // 遍历并转换所有根节点
    option.value = opt.map(node=>{
      return traverse(node)
    });
  }
  // 转换数据结构为n-cascader所接受的格式（将name和parentName转换为label，并移除不必要的字段）
  const traverse = (node) => {
    const { id, name, children } = node;
    // 如果children数组为空，则不返回children字段
    const processedNode = {
      value: id.toString(),
      label: name,
      ...(children.length > 0 ? { children: children.map(child => traverse(child)) } : {})
    };
    return processedNode;
  };
  const queryBrandList = async () => {
    loading.value = true
    try {
      const res = await api.findAllProductBrand()
      if(res.code === 200) {
        res.data.map((item)=>{
          brands.value.push({
            label: item.name,
            value: item.id
          })
        })
      }
      else {
        $message.error(res.message)
      }
    } catch (err) {
      $message.error("获取仓库信息失败！")
    }finally{
      loading.value = false
    }
  }
  const suppliers=ref([])
  const querySupplierList = async () => {
    loading.value = true
    try {
      const res = await api.findAllSupplier()
      if(res.code === 200) {
        res.data.map((item)=>{
          suppliers.value.push({
            label: item.name,
            value: item.id
          })
        })
      }
      else {
        $message.error(res.message)
      }
    } catch (err) {
      $message.error("获取仓库信息失败！")
    }finally{
      loading.value = false
    }
  }
  const queryAttributeList = async () => {
    loading.value = true
    try {
      const res = await api.findAllProductAttribute()
      if(res.code === 200) {
        res.data.map((item)=>{
          const specification = item.specification != null ? item.specification.toString() : 'null';
          const color = item.color != null ? item.color.toString() : 'null';
          const material = item.material != null ? item.material.toString() : 'null';
          const all = specification +"/"+ color +"/"+ material;
          console.log(all);
          attributes.value.push({
            label: all,
            value: item.id
          })
        })
      }
      else {
        $message.error(res.message)
      }
    } catch (err) {
      $message.error("获取属性信息失败！")
    }finally{
      loading.value = false
    }
  }
    onMounted(()=>{
      querySupplierList()
      queryAllProductCategory()
      queryBrandList()
      queryAttributeList()
    })
</script>

<style scoped>
    .form-container {
        display: flex;
        flex-direction: column;
        width: 100%;
        position: relative;
    }

    .image-upload {
        width: 150px;
        height: 150px;
        border: 2px dashed #d9d9d9;
        display: flex;
        justify-content: center;
        align-items: center;
        cursor: pointer;
    }

    .upload-placeholder {
        color: #999;
        font-size: 14px;
        text-align: center;
    }

    .uploaded-image {
        width: 100%;
        height: 100%;
        object-fit: cover;
    }

    .form-row {
        display: flex;
        gap: 10px;
        align-items: center;
        width: 100%;
    }

    .form-row > n-form-item {
        flex: 1;
    }

    .submit-row {
        justify-content: center;
        display: flex;
        width: 100%;
    }
    .image-container {
        position: relative;
        display: inline-block; /* 确保容器宽度适应内容 */
    }

    .delete-icon {
        position: absolute;
        top: 0;
        right: 0;
        padding: 5px; /* 根据需要调整内边距 */
        cursor: pointer;
        /* 添加背景、颜色、大小等其他样式 */
        background-color: rgba(255, 0, 0, 0.5); /* 红色半透明背景 */
        color: white; /* 图标颜色 */
        border-radius: 50%; /* 圆角 */
        display: flex;
        align-items: center;
        justify-content: center;
        /* 隐藏图标，直到需要显示时（例如，在鼠标悬停时） */
        opacity: 0;
        transition: opacity 0.3s ease; /* 添加过渡效果 */
    }

    .image-container:hover .delete-icon {
        /* 鼠标悬停时显示图标 */
        opacity: 1;
    }
</style>
